package cn.itsource.user.service.impl;

import cn.itsource.basic.basic.BusinessException;
import cn.itsource.basic.dto.LoginDto;
import cn.itsource.basic.jwt.JwtUtils;
import cn.itsource.basic.jwt.LoginData;
import cn.itsource.basic.jwt.RsaUtils;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.HttpUtil;
import cn.itsource.basic.util.Md5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.system.domain.Menu;
import cn.itsource.user.constant.WxConstants;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.Wxuser;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.mapper.WxuserMapper;
import cn.itsource.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String checkPass = loginDto.getCheckPass();
        // 校验空值
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(checkPass)){
            throw new BusinessException("所填信息不能为空");
        }

        //校验登录信息
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null) {
            throw new BusinessException("账号或密码错误，请重新输入");
        }

        //对密码进行加密加盐
        String inputPwd = Md5Utils.encrypByMd5(checkPass + logininfo.getSalt());
        if (!inputPwd.equals(logininfo.getPassword())) {
            throw new BusinessException("账号或密码错误，请重新输入");
        }

        //校验是否被禁用
        if (!logininfo.getDisable()) {
            throw new BusinessException("账号已被禁用，请联系管理员进行解封操作");
        }

        //使用jwtToken将用户信息加密，返回给前端
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        //1.根据code发送第二个请求：httpUtil，返回jason字符串
        //a.准备第二个请求和参数
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                                            .replace("SECRET", WxConstants.SECRET)
                                            .replace("CODE", code);
        //调用工具类返回一个json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);

        /*{
        "access_token":"ACCESS_TOKEN",
        "expires_in":7200,
        "refresh_token":"REFRESH_TOKEN",
        "openid":"OPENID",
        "scope":"SCOPE",
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }*/
        //2.使用fastjson将json格式的字符串转换为一个对象：获取到令牌（token）和openid
        JSONObject obj = JSONObject.parseObject(jsonStr);
        String access_token = obj.getString("access_token");
        String openid = obj.getString("openid");

        //3.根据openid查询t_wxuser表
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        //a.在扫过二维码进行手机绑定之后就直接免密登录（不需要在页面输入用户名和密码即可登录）
        //如果查询到了一个已经存在的微信用户，就去找到它相关联的user对象
        if (wxuser != null) {
            //当wxuser存在之后就会自动绑定user_id
            User user = userMapper.findById(wxuser.getUserId());
            //当他关联的user对象也有了之后就说明已经绑定过了，后续直接扫码免密登录即可
            if (user != null) {
                Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());
                //使用jwtToken将用户信息加密，返回给前端
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setResultObj(map);
            }
        }
        //b.如果没有查询到就直接跳转到绑定页面
        return AjaxResult.me().setSuccess(false).setResultObj("?access_token=" + access_token + "&openid=" + openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        /*phone:"13330964748",
        verifyCode:"",
        accessToken:"",
        openId:""*/
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");

        //校验空值
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("所填信息不能为空");
        }
//        if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openId)){
//            throw new BusinessException("请进行扫码登陆");
//        }

        //校验验证码是否过期
        Object phoneCode = redisTemplate.opsForValue().get("binder" + phone);
        if (phoneCode == null){
            throw new BusinessException("手机验证码已过期,请重新获取");
        }

        //校验验证码是否正确
        if (!phoneCode.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码错误");
        }

        //组装第三个请求的url地址
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                                             .replace("OPENID",openId);

        //发送HTTP请求，并且返回一个json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);

        //将json格式的字符串转换为wxuser对象
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);

        //根据电话获取【注册过但没有绑定微信的手机号】或是新建一个user对象【logininfo对象添加】，并将user对象添加到数据库
        User user = userMapper.findByPhone(phone);
        //对没有注册过的手机新建一个user
        if (user == null){
            //先创建user对象
            user = phone2User(phone);
            //再创建logininfo对象
            Logininfo logininfo = user2Logininfo(user);

            //先保存logininfo对象
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            //再保存user对象
            userMapper.add(user);
        }

        //将userid设置到Wxuser对象中，并将wxuser设置到数据库
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);

        //免密登录
        Logininfo logininfoTemp = logininfoMapper.findById(user.getLogininfoId());
        //使用jwtToken将用户信息加密，返回给前端
        Map<String, Object> mapTemp = loginSuccessJwtHandler(logininfoTemp);

        return AjaxResult.me().setResultObj(mapTemp);
    }

    private Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        //需要获取jwttoken，logininfo，登陆人的权限，登陆人的菜单
        //用户登录时不需要权限和菜单，因此需要先对登陆人进行判断
        //将相关数据放到map集合中
        Map<String, Object> map = new HashMap<>();
        //在logindata中获取登录信息，权限和菜单
        LoginData loginData = new LoginData();
        //先将登录信息放进去
        map.put("logininfo",logininfo);
        //在登录数据中设置登录信息
        loginData.setLogininfo(logininfo);
        //判断登录人角色--管理员
        if (logininfo.getType() == 0){
            //获取当前登录人的权限，需要通过logininfo的id来获取
            List<String> permissions = employeeMapper.getSns(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //获取当前登录人菜单，需要通过logininfo的id来获取
            List<Menu> menus = employeeMapper.getMenus(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        //对logindata(logininfo + permissions + menus)进行加密操作
        try {
            //用私钥进行加密
            PrivateKey privateKey = RsaUtils.getPrivateKey(LogininfoServiceImpl.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //设置过期时间
            String token = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 3000);
            map.put("token",token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //位用户设置一个随机的六位验证码，可以通过短讯或者邮箱告诉用户（后面扫码都是直接通过微信扫码，不用输密码）
        String randomPwd = StrUtils.getComplexRandomString(6);
        Md5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(randomPwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        /*
        *{
        "openid":"OPENID",
        "nickname":"NICKNAME",
        "sex":1,
        "province":"PROVINCE",
        "city":"CITY",
        "country":"COUNTRY",
        "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
        "privilege":[
        "PRIVILEGE1",
        "PRIVILEGE2"
        ],
        "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"`
        }
        */
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        //性别已经被微信官方所屏蔽
        wxuser.setSex(Integer.parseInt(obj.getString("sex")));
        //地址
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));
        return wxuser;
    }
}
